﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using System.Text;
using Z.Nlayer.Utility;
using Z.Nlayer.Utility.Encrypt;
using Newtonsoft.Json;
using SQLitePCL;
using Z.Nlayer.Infrastructure.Utility.BaseEnums;
using Company.Project.Infrastructure.Common;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Company.Project.Web.Api.Lib
{
    public class BaseApiController : Controller
    {
        public async Task<APITipResult> Do<T>(Func<T, APITipResult, Task> runMethod)
        {
            var result = new APITipResult();
            try
            {
                var parm = typeof(DetectionParamHelper).GetMethod("Decrypt").MakeGenericMethod(typeof(T)).Invoke((new DetectionParamHelper()), new[] { Request.HttpContext.Items["ApiParmer"] });
                await runMethod((T)parm, result);
                result.code = Enum_ApiResultCode.Succ.GetValueToInt();
            }
            catch (Exception e)
            {
                if (e.GetBaseException().GetType() == typeof(CustomException))
                {
                    var custexception = ((CustomException)e.GetBaseException());
                    result.code = custexception.code == 0 ? Enum_ApiResultCode.OtherErr.GetValueToInt() : custexception.code;
                    result.message = custexception.message ?? custexception.Message;
                }
                else
                {
                    result.code = Enum_ApiResultCode.OtherErr.GetValueToInt();
                    result.message = e.InnerException?.Message ?? e.Message;
                }
            }
            return result;
        }
    }
}
